package com.yonyou.pmclouds.workstopreport.process;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonMaintain;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonQuery;
import com.yonyou.pmclouds.workstopreport.entity.WorkStopVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WorkStopCopyPersonUpdateBatchProcessor implements SingleProcessor<WorkStopVO> {

    @Autowired
    private ICopyPersonMaintain copyPersonMaintain;

    @Autowired
    private ICopyPersonQuery iCopyPersonQuery;

    @Override
    public void process(WorkStopVO vo, WorkStopVO orig) throws BusinessException {
        List<CopyPersonVO> currentVOs = vo.getCopyPersons();
        List<String> ids = new ArrayList<>();
        ids.add(vo.getPkWorkstopreport());
        List<CopyPersonVO> copyPersonsDB = iCopyPersonQuery.queryByPkBills(ids);

        Map<String,CopyPersonVO> current = new HashMap<>();
        Map<String,CopyPersonVO> db = new HashMap<>();

        for(CopyPersonVO copyPersonVO : currentVOs){
            current.put(copyPersonVO.getCopyPerson(),copyPersonVO);
        }

        for(CopyPersonVO copyPersonVO : copyPersonsDB){
            db.put(copyPersonVO.getCopyPerson(),copyPersonVO);
        }

        List<CopyPersonVO> insertVOS = new ArrayList<>();
        List<CopyPersonVO> deleteVOS = new ArrayList<>();

        for(CopyPersonVO copyPersonVO : copyPersonsDB){
            if(null == current.get(copyPersonVO.getCopyPerson())){
                copyPersonVO.setPkBill(vo.getPkWorkstopreport());
                deleteVOS.add(copyPersonVO);
            }
        }

        for(CopyPersonVO copyPersonVO : currentVOs){
            if(null == db.get(copyPersonVO.getCopyPerson())){
                copyPersonVO.setPkBill(vo.getPkWorkstopreport());
                insertVOS.add(copyPersonVO);
            }
        }

        if(null != insertVOS && insertVOS.size() > 0){
            copyPersonMaintain.insertBatch(insertVOS);
        }

        if(null != deleteVOS && deleteVOS.size() > 0){
            copyPersonMaintain.deleteBatchForCopypersion(deleteVOS,vo.getPkWorkstopreport());
        }
    }
}




